package com.bh.ly.oa.adapter;

import java.io.IOException;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bh.ly.oa.GlobalData;
import com.bh.ly.oa.R;
import com.bh.ly.oa.util.Util;
import com.dd.plist.NSArray;
import com.dd.plist.NSDictionary;
import com.dd.plist.NSString;
import com.dd.plist.PropertyListParser;

public class MenuAdapter extends BaseAdapter {

	private Context context;
	
//	private ListActivity
	
	private NSArray menuListArray;
	
	public MenuAdapter(Context contex)
	{
		this.context = contex;
		
		try {
			if (GlobalData.getInstance().getMenuListArray() != null) {
				menuListArray = GlobalData.getInstance().getMenuListArray();
			} else {
			    menuListArray = (NSArray) PropertyListParser.parse(contex.getAssets().open("menuData.plist"));
			    GlobalData.getInstance().setMenuListArray(menuListArray);
			}
		} catch (IOException e) {
			Toast.makeText(contex, "open assets erro:"+e.getMessage(), 30);
			e.printStackTrace();
		} catch (Exception e) {
			Toast.makeText(contex, "has erro:"+e.getMessage(), 30);
			e.printStackTrace();
		}
		
		if(menuListArray==null)
			menuListArray = new NSArray(1);
	}
	
	@Override
	public int getCount() {
		return menuListArray.count();
	}

	@Override
	public Object getItem(int position) {
		return menuListArray.objectAtIndex(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		
		final MenuItem item;
		if(convertView==null)
		{
			item = new MenuItem();
			convertView = LayoutInflater.from(context).inflate(R.layout.menu_item, null);
			item.icon = (ImageView) convertView.findViewById(R.id.icon);
			item.name = (TextView) convertView.findViewById(R.id.name);
			convertView.setTag(item);
			
		}else 
		{
			item = (MenuItem) convertView.getTag();
		}
		
		NSDictionary dictionary = (NSDictionary) menuListArray.objectAtIndex(position);
		String name = ((NSString)dictionary.objectForKey("menuname")).getContent();
		String icon = ((NSString)dictionary.objectForKey("menuimage")).getContent();
		item.name.setText(name);
		item.index = position;
		item.items = (NSArray) dictionary.objectForKey("submenes");
		
		int resId = Util.getDrawableByName(icon);
		item.icon.setImageResource(resId);
//		try {
//			item.icon.setImageBitmap(BitmapFactory.decodeStream(context.getAssets().open(icon)));
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		
		return convertView;
	}
	
	class MenuItem {
		
		ImageView icon;
		TextView name;
		int index;
		NSArray items;
	}

}
